package org.catpay.modules.app.service.impl;

import java.math.BigDecimal;
import java.util.List;

import org.catpay.modules.app.entity.IncomeRuleEntity;
import org.catpay.modules.app.entity.OrderDataEntity;
import org.catpay.modules.app.entity.UserEntity;
import org.catpay.modules.app.service.AccService;
import org.catpay.modules.app.service.IncomeRuleService;
import org.catpay.modules.app.service.RewardService;
import org.catpay.modules.app.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.mapper.EntityWrapper;

import lombok.extern.slf4j.Slf4j;

@Service("rewardService")
@Slf4j
public class RewardServiceImpl implements RewardService {
	@Autowired
	UserService uService;
	@Autowired
	AccService aService;
	@Autowired
	IncomeRuleService incomeRuleService;

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void doReward(OrderDataEntity order) {
		for (IncomeRuleEntity rule : getIncomeRule(order.getGoodsId())) {
			if (order.getTotalCount() == 0 || order.getTotalCount() < rule.getCond())
				continue;
			UserEntity benUser = uService.getUser(order.getUserId());
			if (benUser == null) {
				log.error("用户ID" + order.getUserId() + "找不到");
				continue;

			}
			switch (rule.getUserChose()) {
			// 奖励给谁 1本人2推荐人3推荐人的推荐人4
			case 1:

				if (benUser.getRole() == rule.getToPatherRole() && benUser.getLevel() == rule.getToPatherLevel()) {
					BigDecimal amount = new BigDecimal(0.00);
					String aum = rule.getAumt();
					if (aum.contains("%")) {
						amount = new BigDecimal(aum.split("%")[0]).multiply(order.getAmount())
								.divide(new BigDecimal(100.00));
					} else {
						amount = new BigDecimal(aum);
					}
					
					benUser.setProfitBalance(amount.add(benUser.getProfitBalance()));
					benUser.setAccountBalance(amount.add(benUser.getAccountBalance()));
					benUser.updateById();
					
					String rules = "规则:" + rule.getId();
					String remark = new StringBuffer().append(benUser.getNickName()).append(",购买：")
							.append(order.getGoodsName()).append("数量：").append(order.getTotalCount()).append("获得:")
							.append(amount).append("元奖励。").toString();
					aService.addUserIncome(benUser.getId(), amount, order.getOrderNo(), "5", benUser.getId(), rules,
							remark);
				} else {
					log.info("无需奖励:" + order.getOrderNo());
				}
				break;
			case 2:
				UserEntity fatherUser = uService.getUser(benUser.getFatherId());
				if (fatherUser.getRole() == rule.getToPatherRole()
						&& fatherUser.getLevel() == rule.getToPatherLevel()) {
					BigDecimal amount = new BigDecimal(0.00);
					String aum = rule.getAumt();
					if (aum.contains("%")) {
						amount = new BigDecimal(aum.split("%")[0]).multiply(order.getAmount())
								.divide(new BigDecimal(100.00));
					} else {
						amount = new BigDecimal(aum);
					}
					fatherUser.setProfitBalance(amount.add(fatherUser.getProfitBalance()));
					fatherUser.setAccountBalance(amount.add(fatherUser.getAccountBalance()));
					fatherUser.updateById();
					String rules = "规则:" + rule.getId();
					String remark = new StringBuffer().append("因下级:").append(benUser.getNickName()).append(",购买：")
							.append(order.getGoodsName()).append(",数量：").append(order.getTotalCount() + ",")
							.append(fatherUser.getNickName()).append("获得:").append(amount).append("元奖励。").toString();
					aService.addUserIncome(fatherUser.getId(), amount, order.getOrderNo(), "5", fatherUser.getId(),
							rules, remark);
				} else {
					log.info("无需奖励:" + order.getOrderNo());
				}
				break;
			case 3:
				break;
			}
		}
	}

	@Override
	public List<IncomeRuleEntity> getIncomeRule(Long goodsId) {
		return incomeRuleService.selectList(new EntityWrapper<IncomeRuleEntity>().eq("goods_id", goodsId)
				.ne("status", -1).orderBy("create_time", false));
	}

}
